#include "Mesh.h"
#include <iostream>

float boxX = 1.0;
float boxY = 1.0;
float boxZ = 1.0;

float minBoxX = -1.0;
float minBoxY = -1.0;
float maxBoxX = 1.0;
float maxBoxY = 1.0;

Mesh::Mesh()
{
	VAO = 0;
	VBO = 0;
	IBO = 0;
	indexCount = 0;
}

void Mesh::CreateMesh(GLfloat *vertices, unsigned int *indices, unsigned int numOfVertices, unsigned int numOfIndices)
{
	indexCount = numOfIndices;

	glGenVertexArrays(1, &VAO);
	glBindVertexArray(VAO);

	glGenBuffers(1, &IBO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices[0]) * numOfIndices, indices, GL_STATIC_DRAW);

	glGenBuffers(1, &VBO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices[0]) * numOfVertices, vertices, GL_STATIC_DRAW);

	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(vertices[0]) * 8, 0);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(vertices[0]) * 8, (void*)(sizeof(vertices[0]) * 3));
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(vertices[0]) * 8, (void*)(sizeof(vertices[0]) * 5));
	glEnableVertexAttribArray(2);

	float minX = 1000;
	float maxX = -1000;
	float minY = 1000;
	float maxY = -1000;
        float minZ = 1000;
	float maxZ = -1000;

        for(int i=0;i<numOfIndices/8;i++)
        {
            float x = vertices[i*8+0];
	    float y = vertices[i*8+1];
	    float z = vertices[i*8+2];
	    minX = std::min(x,minX);
	    minY = std::min(y,minY);
	    minZ = std::min(z,minZ);

	    maxX = std::max(x,maxX);
	    maxY = std::max(y,maxY);
	    maxZ = std::max(z,maxZ);
	}
	
        boxX = maxX - minX;
	boxY = maxY - minY;
	boxZ = maxZ - minZ;

	minBoxX = minX;
	minBoxY = minY;
	maxBoxX = maxX;
	maxBoxY = maxY;

        std::cout<<boxX<<" "<<boxY<<" "<<boxZ<<"\n";
	  
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

	glBindVertexArray(0);
}

void Mesh::RenderMesh()
{
	glBindVertexArray(VAO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
	glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	glBindVertexArray(0);
}

void Mesh::ClearMesh()
{
	if (IBO != 0)
	{
		glDeleteBuffers(1, &IBO);
		IBO = 0;
	}

	if (VBO != 0)
	{
		glDeleteBuffers(1, &VBO);
		VBO = 0;
	}

	if (VAO != 0)
	{
		glDeleteVertexArrays(1, &VAO);
		VAO = 0;
	}

	indexCount = 0;
}


Mesh::~Mesh()
{
	ClearMesh();
}
